import axios from 'axios';

const api = axios.create({
  baseURL: '/api',
  timeout: 5000,
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    // 如果响应成功，直接返回数据
    if (response.status >= 200 && response.status < 300) {
      return response.data;
    }
    return Promise.reject(new Error(response.data.message || '请求失败'));
  },
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
);

// 认证相关
export const auth = {
  login: (data: { username: string; password: string }) =>
    api.post('/api/auth/login', data),
  register: (data: { username: string; password: string; email: string }) =>
    api.post('/api/auth/register', data),
  logout: () => {
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  },
  getCurrentUser: () => {
    const userStr = localStorage.getItem('user')
    return userStr ? JSON.parse(userStr) : null
  },
  isAuthenticated: () => {
    return !!localStorage.getItem('token')
  },
  getToken: () => {
    return localStorage.getItem('token')
  }
};

// 商品相关
export const products = {
  getList: () => api.get('/api/products'),
  getById: (id: string) => api.get(`/api/products/${id}`),
  create: (data: any) => api.post('/api/products', data),
  update: (id: string, data: any) => api.put(`/api/products/${id}`, data),
  delete: (id: string) => api.delete(`/api/products/${id}`),
};

// 分类相关
export const categories = {
  getList: () => api.get('/api/categories'),
  getById: (id: string) => api.get(`/api/categories/${id}`),
  create: (data: any) => api.post('/api/categories', data),
  update: (id: string, data: any) => api.put(`/api/categories/${id}`, data),
  delete: (id: string) => api.delete(`/api/categories/${id}`),
};

// 订单相关
export const orders = {
  getList: () => api.get('/api/orders'),
  getById: (id: string) => api.get(`/api/orders/${id}`),
  update: (id: string, data: any) => api.put(`/api/orders/${id}`, data),
};

// 管理员相关
export const admins = {
  getList: () => api.get('/api/admins'),
  getById: (id: string) => api.get(`/api/admins/${id}`),
  create: (data: any) => api.post('/api/admins', data),
  update: (id: string, data: any) => api.put(`/api/admins/${id}`, data),
  delete: (id: string) => api.delete(`/api/admins/${id}`),
};

// 仪表盘数据
export const dashboard = {
  getStats: () => api.get('/api/dashboard/stats'),
  getSalesData: () => api.get('/api/dashboard/sales'),
  getCategoryStats: () => api.get('/api/dashboard/categories'),
};

export default api; 